package cn.kgc.student.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.JSONSerializerMap;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController
public class LoginController {
    @Resource
    private StringRedisTemplate template;

    @RequestMapping("/getValidCode.do")
    public Map getValidCode(String mobile) throws IOException {
        String account = "15351607783";
        String ts = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String pswd= DigestUtils.md5DigestAsHex(("15351607783Msy_7783"+ts).getBytes());
        Random rd = new Random();
        String validCode = ""+rd.nextInt(10)+rd.nextInt(10)+rd.nextInt(10)+rd.nextInt(10)+rd.nextInt(10)+rd.nextInt(10);
        String msg = "您的验证码是"+validCode+"，如非本人操作，请忽略本短信！";
        Map params = new HashMap();
        params.put("account",account);
        params.put("ts",ts);
        params.put("pswd",pswd);
        params.put("mobile",mobile);
        params.put("msg",msg);
        //通过短信平台发送短信
        String rep = ZxHttpUtil.sendPostMessage("http://139.196.108.241:8080/Api/HttpSendSMYzm.ashx", params, "UTF-8");
        Map reply = JSON.parseObject(rep,Map.class);
        if((Integer)reply.get("result")==0){
            //如果短信平台发送成功，把验证码保存到redis缓存中，有效时间是30秒
            Map result = new HashMap();
            result.put("flag",true);
            result.put("msg","验证码已发送，请在30秒内输入");
            template.opsForValue().set("login:validCode:"+mobile,validCode,30, TimeUnit.SECONDS);
            return result;
        }else{
            //如果短信平台发送失败，提示
            Map result = new HashMap();
            result.put("flag",false);
            result.put("msg","验证码发送失败");
            return result;
        }
    }

    @RequestMapping("/checkValidCode.do")
    public Map getValidCode(String mobile,String validCode) throws IOException {
        Map result = new HashMap();
        result.put("flag",false);
        result.put("msg","验证码无效或已过期");
        //从redis缓存中获取该手机号对应的验证码
        String right = template.opsForValue().get("login:validCode:"+mobile);
        if(right==null){//如果redis缓存中没有该手机号对应的key/value
            return result;
        }
        System.out.println(validCode.toString()+" : "+right.toString());
        if(validCode.toString().equals(right.toString())) {
            result.put("flag",true);
            result.put("msg","验证码正确");
            template.delete("login:validCode:"+mobile);
        }
        return result;
    }



}
